<template>
  <div class="map-wrapper">
    <BaseMap
      ref="basemap"
      :mapId="mapId"
      :zoom="zoom"
      :minZoom="minZoom"
      :maxZoom="maxZoom"
      :projection="projection"
      :center="mapCenter"
      :extent="mapExtent"
      :layers="layers"
      @mapPointermove="mapPointermove"
      @mapClick="mapClick"
    >
      <component
        :is="popopCom"
        :opts="popupComOpts"
        @popClose="popClose"
      ></component>
    </BaseMap>
  </div>
</template>
<script>
import 'ol/ol.css'
import BaseMap from '@/_components/map/baseMap'
import mapConfig from '../../../../src/_components/map/mapConfig'
import { getMapBound } from '@/_components/map/api/index.js'
import { onMounted, reactive, ref, toRefs } from 'vue-demi'
import layersData from '../../../analogData/layersData'
import MyMapUtils from '../../../_components/map/mapUtils'
import mapHelper from '../../../_components/map/mapHelper'
export default {
  setup () {
    const state = reactive({
      mapId: 'monitor',
      zoom: mapConfig.mapCfg.zoom,
      minZoom: mapConfig.mapCfg.minZoom,
      maxZoom: mapConfig.mapCfg.maxZoom,
      projection: mapConfig.mapCfg.projection,
      mapCenter: mapConfig.mapCfg.center,
      mapExtent: mapConfig.mapCfg.extent,
      layers: mapConfig.layers,
      layersClick: null,
      adcd: '630000000000000',
      basemap: ref(null),
      rainData: layersData.rainData, // 雨量数据
      riverData: layersData.riverData, // 河道数据
      rsvrData: layersData.rsvrData, // 水库数据
      popupId: 'monitorPopup',
      popopCom: '', // Overlay 里显示的组件
      popupComOpts: {}, // 给Overlay 里显示的组件传递的参数
      hasManuaPopup: false
    })

    // 调用子组件的shadeOthersByJson方法制作一个遮罩层
    const changeUnit = async () => {
      const geoJson = await getMapBound(state.adcd)
      state.basemap.shadeOthersByJson(geoJson)
    }

    // 叠加各类图层
    const addLayers = () => {
      addRainLayers('雨量站', state.rainData)
      addRainLayers('河道站', state.riverData)
      addRainLayers('水库站', state.rsvrData)
    }

    const addRainLayers = (title, data) => {
      const featuresArr = []
      switch (title) {
        case '雨量站':
          data.map((item) => {
            if (item.lgtd && item.lttd) {
              const style = MyMapUtils.createStyle('', '', '#3380f3', null, '20', '0', [12, 12], getRianColorByDrp(item.drps))
              const feature = MyMapUtils.createFeature(item.lgtd, item.lttd, title, style, item)
              featuresArr.push(feature)
            }
          })
          break
        case '河道站':
          data.map((item) => {
            if (item.lgtd && item.lttd) {
              const style = MyMapUtils.createStyle(
                '',
                process.env.BASE_URL + 'images/yj-marker-' + (item.warnLevel || '0') + '.png',
                ' #3380f3',
                null,
                null,
                null,
                [20, 20]
              )
              const feature = MyMapUtils.createFeature(item.lgtd, item.lttd, title, style, item)
              featuresArr.push(feature)
            }
          })
          break
        case '水库站':
          if (data.length > 0) {
            data.map((item) => {
              if (item.lgtd && item.lttd) {
                const style = MyMapUtils.createStyle('', process.env.BASE_URL + 'images/rsvrBlue-12.gif', '#3380f3', null, null, null, [12, 12])
                const feature = MyMapUtils.createFeature(item.lgtd, item.lttd, title, style, item)
                featuresArr.push(feature)
              }
            })
          }
          break
      }
      MyMapUtils.setLayerData(mapHelper, title, featuresArr)
    }

    const getRianColorByDrp = (val = 0) => {
      let color = '#000'
      val = parseFloat(val)
      if (val >= 0 && val <= 10) {
        color = '#97F297'
      } else if (val > 10 && val <= 25) {
        color = '#3DCE3D'
      } else if (val > 25 && val <= 50) {
        color = '#6ACEF2'
      } else if (val > 50 && val <= 100) {
        color = '#1010F2'
      } else if (val > 100 && val <= 250) {
        color = '#F210F2'
      } else if (val > 250) {
        color = '#A0103D'
      }
      return color
    }

    // 地图移动事件 筛选图层 （优先获取可以点击的图层）
    const mapPointermove = (evt) => {
      if (evt.dragging) {
        return
      }
      const layersTitle = state.layersClick.map((item) => item.title)
      const featruesTag = MyMapUtils.getFeaturesBindTitlesByEvt(window.map, evt, layersTitle)
      const layerCfg = mapConfig.getLayerItem(Object.keys(featruesTag)[0])

      if (Object.keys(featruesTag).length > 0) {
        window.map.getTargetElement().style.cursor = 'pointer'
        const targetFeature = featruesTag[Object.keys(featruesTag)[0]][0]
        const targetClassify = getClassify(targetFeature.getProperties())
        if (targetClassify.com) {
          // --widget
          if (targetClassify.manuaClose) {
            state.hasManuaPopup = true
          }
          popOpen(targetFeature, targetClassify, evt.pixel)
        } else if (layerCfg) {
          // --tip
          const text = targetClassify.tipText || targetFeature.get(layerCfg.floatMark)
          MyMapUtils.createTips(mapHelper, targetFeature, text)
        } else {
          popClose()
          MyMapUtils.closeTips(window.map)
          window.map.getTargetElement().style.cursor = 'default'
        }
      } else {
        popClose()
        MyMapUtils.closeTips(window.map)
        window.map.getTargetElement().style.cursor = 'default'
      }
    }

    // 地图点击事件
    const mapClick = (evt) => {
      const canClickLayerTitle = state.layersClick.map((item) => {
        return item.title
      })
      const clickLayers = {}
      window.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
        const title = layer.get('title')
        if (canClickLayerTitle.includes(title)) {
          if (!clickLayers[title]) clickLayers[title] = []
          clickLayers[title].push(feature)
        }
      })
      const layerTitleArr = Object.keys(clickLayers)
      if (layerTitleArr.length > 0) {
        const features = clickLayers[layerTitleArr[0]]
        if (features && features.length) {
          const feature = features[0]
          const params = feature.getProperties()

          // // --根据feature 所在图层 返回业务分类及相关组件信息
          // const classify = this.getClassify(features[0])
          delete params.geometry
          // --空间数据库，渲染的点 feature 没有layerNm ,此处特殊处理一下
          if (!params.layerNm) params.layerNm = layerTitleArr[0]
          const classify = getClassify(params)
          // 注意此处 classify.url 为外弹窗参数 classify.customParams 为本页弹窗
          if (classify.url) {
            window.open(classify.url, '_blank')
          } else {
            // 把参数丢出去（可以在此把点击事件抛出去【indexOver页面中处理】，也可以在此直接弹出弹出窗口）
            popOpen(feature, classify, evt.pixel)
          }
        }
      }
    }

    const popOpen = (feature, classify, pixel) => {
      const el = document.querySelector('.map-wrapper .ol-popup')
      const popup = MyMapUtils.createOverlay(window.map, state.popupId, el)
      // ---------change positon by class start
      let position1 = 'bottom'
      let position2 = 'center'
      const width = document.querySelector('.map-wrapper').clientWidth
      if (pixel[1] < 320) position1 = 'top'
      if (pixel[0] < 350) position2 = 'left'
      if (width - pixel[0] < 350) position2 = 'right'
      popup.setPositioning(position1 + '-' + position2)
      el.className = `ol-popup ol-popup-${position1}-${position2}`
      // ---------change positon by class end
      state.popopCom = classify.com
      state.popupComOpts = classify.paramData
      MyMapUtils.openPop(popup, feature)
    }

    // 关闭popover窗
    const popClose = () => {
      state.hasManuaPopup = false
      MyMapUtils.closePop(window.map, state.popupId)
    }

    const getClassify = (params) => {
      // 根据feature 所在图层 返回pop要显示的组件信息
      if (!Object.keys(params).length) {
        return
      }
      let classify = null
      // 创建实体要素的时候设置的属性，如：mapUtils.createFeature
      switch (params.layerNm) {
        case '雨量站':
          classify = {
            name: params.layerNm,
            com: '', // popup: RainPop
            tipText: `${params.stnm} (${params.stlvlnm}) (${params.drps} mm)`,
            url: '',
            paramData: {
              ...params
            }
          }
          break
        case '河道站':
          classify = {
            name: params.layerNm,
            com: 'RiverPop', // popup: RainPop
            manuaClose: true,
            url: '',
            paramData: {
              ...params
            }
          }
          break
        case '水库站':
          classify = {
            name: params.layerNm,
            com: 'RsvrPop', // popup: RainPop
            manuaClose: true,
            url: '',
            paramData: {
              ...params
            }
          }
          break
      }
      return classify
    }

    onMounted(() => {
      changeUnit()
      addLayers()
      state.layersClick = mapConfig.getClickLayers()
    })

    return {
      ...toRefs(state),
      mapPointermove,
      mapClick,
      getClassify,
      popOpen
    }
  },
  components: {
    BaseMap,
    RiverPop: () => import('../../../components/RiverPop'),
    RsvrPop: () => import('../../../components/RsvrPop')
  }
}
</script>
<style scoped lang="scss">
@import '../../../css/main.scss';
.map-wrapper {
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  background-size: 100% 100%;
  background-clip: border-box;
  position: relative;
}

</style>
